//
//  FaceCreateViewController.m
//  TestAispeech
//
//  Created by shaowei on 13-9-8.
//  Copyright (c) 2013年 LianZhan. All rights reserved.
//

#import "FaceSetPwdViewController.h"
#import "MBProgressHUD.h"
#import "FaceImageHandle.h"


@interface FaceSetPwdViewController ()

@property (nonatomic,retain) UIButton *btnOfUsing;
@property (nonatomic,retain) PersonModel *personInfo;

@end

@implementation FaceSetPwdViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_personInfo release];
    Block_release(_completeBlock);
    [_faceID1 release];
    [_faceID2 release];
    [_faceID3 release];
    [_btnOfUsing release];
    [_btnOfImage1 release];
    [_btnOfImage2 release];
    [_btnOfImage3 release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setBtnOfImage1:nil];
    [self setBtnOfImage2:nil];
    [self setBtnOfImage3:nil];
    [super viewDidUnload];
}

#pragma mark Function - Private

- (BOOL)checkPictureProgress{
    return (_faceID1.length && _faceID2.length && _faceID3.length );
}

- (void)setFaecID:(NSString *)faceID withTag:(int)tag{
    switch (tag) {
        case 1:{
            self.faceID1 = faceID;
        }
            break;
        case 2:{
            self.faceID2 = faceID;
        }
            break;
        case 3:{
            self.faceID3 = faceID;
        }
            break;
            
        default:
            break;
    }
}

- (BOOL)addFaceToPerson{
    NSArray *faceIDArr = @[_faceID1,_faceID2,_faceID3];
    
    //这里的人名，可由用户自己输入，这里为方便设置为随机的
    NSString *nameCreate = [@"test" stringByAppendingFormat:@"%d",arc4random()%10000];
    FaceppResult *result =  [[FaceppAPI person] createWithPersonName:nameCreate
                                   andFaceId:faceIDArr
                                      andTag:nil
                                  andGroupId:nil
                                 orGroupName:nil];
    NSLog(@"SW - person_id:%@",[result content]);
    
    NSString *person_id = [result content][@"person_id"];
    NSString *person_name = [result content][@"person_name"];
    if (person_id && person_name) {
        //任务创建成功
        self.personInfo = [[[PersonModel alloc] init] autorelease];
        _personInfo.person_id = person_id;
        _personInfo.person_name = person_name;
        return YES;
    }else{
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"人物模型创建成功"
                                                     message:nil
                                                    delegate:nil
                                           cancelButtonTitle:@"确定"
                                           otherButtonTitles: nil];
        [av show];
        [av release];
        return NO;
    }
}

- (BOOL)verifyFaceImage{
    //添加人脸成功，开始训练人脸识别
    FaceppResult * result = [[FaceppAPI train] trainSynchronouslyWithId:_personInfo.person_id
                                         orName:_personInfo.person_name
                                        andType:FaceppTrainVerify
                                refreshDuration:3
                                        timeout:20];
    
    return result.success;
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    UIImage *sourceImage = info[UIImagePickerControllerOriginalImage];
    UIImage *imageToDisplay = [FaceImageHandle fixOrientation:sourceImage];
    
    //异步后台线程运行
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        FaceppResult *result = [[FaceppAPI detection] detectWithURL:nil
                                                        orImageData:UIImageJPEGRepresentation(imageToDisplay, 0.8f)
                                                               mode:FaceppDetectionModeNormal
                                                          attribute:FaceppDetectionAttributeNone];
        
        //回到前台主线程执行
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (result.success && [[result content][@"face"] count]) {
                //识别成功---此处只能识别一个头像
                [self setFaecID:[[result content][@"face"] lastObject][@"face_id"]
                        withTag:_btnOfUsing.tag];
                UIImage *resultImage = [FaceImageHandle detectWithImage:imageToDisplay andFcaeData:[result content]];
                [_btnOfUsing setImage:resultImage forState:UIControlStateNormal];
            }else{
                ALERT_VIEW(@"头像识别失败，请重试", nil);
            }
            
            
            
        }) ;
    });
    
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissModalViewControllerAnimated:YES];
}

- (void)savePictureToPerson:(NSArray *)imageArray{
    
}

#pragma mark - action

- (IBAction)actionTakePicture:(id)sender {
    self.btnOfUsing = (UIButton *)sender;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;//前置摄像头
        [self presentModalViewController:imagePicker animated:YES];
        [imagePicker release];
    } else {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"failed to camera"
                              message:@""
                              delegate:nil
                              cancelButtonTitle:@"OK!"
                              otherButtonTitles:nil];
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
        [alert release];
        
    }
}

- (IBAction)actionFinish:(id)sender {
    if ([self checkPictureProgress]) {
        //拍摄成功
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        //异步后台线程运行
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            if ([self addFaceToPerson]) {
                if ([self verifyFaceImage]) {
                    //参数回调
                    if (_completeBlock) {
                        _completeBlock(_personInfo,YES);
                    }
                    
                }else{
                    ALERT_VIEW(@"训练失败",nil);
                }
                
            }else{
                ALERT_VIEW(@"创建失败",nil);
            }
            
            //回到前台主线程执行
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }) ;
            
            
        });
        
    }else{
        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"请完成3张头像的拍摄才能完成"
                                                     message:nil
                                                    delegate:nil
                                           cancelButtonTitle:@"确定"
                                           otherButtonTitles: nil];
        [av show];
        [av release];
    }
        
}

@end
